#!/bin/sh

echo "Preparing to uninstall HyperHDR"

# search for users in system, returns first entry
FOUND_USR=`who | grep -o -m1 '^\w*\b'` || "root"

# stop running daemon before we delete it
HYPERHDR_RUNNING=false
pgrep hyperhdr > /dev/null 2>&1 && HYPERHDR_RUNNING=true

if grep -m1 systemd /proc/1/comm > /dev/null
then
	echo "Stopping HyperHDR daemon: systemd"
	# systemd
	$HYPERHDR_RUNNING && systemctl stop hyperhdr"@${FOUND_USR}" 2> /dev/null
	# disable user specific symlink
	echo "Disabling service and removing entry"
	systemctl -q disable hyperhdr"@${FOUND_USR}"
	
	rm -v /etc/systemd/system/hyperhdr@.service 2>/dev/null	

elif [ -e /sbin/initctl ]
then
	echo "Stopping HyperHDR daemon: upstart"
	# upstart
	$HYPERHDR_RUNNING && initctl stop hyperhdr
	echo "Removing upstart service"
	rm -v /etc/init/hyperhdr* 2>/dev/null
	initctl reload-configuration

else
	echo "Stopping HyperHDR daemon: sysV"
	# sysV
	$HYPERHDR_RUNNING && service hyperhdr stop 2>/dev/null
	echo "Removing sysV service"
	update-rc.d -f hyperhdr remove
	rm /etc/init.d/hyperhdr* 2>/dev/null
fi

# In case we don't use a service kill all instances
killall hyperhdr 2> /dev/null

# delete desktop icons; desktop-file-edit is a workaround to hide the entry and delete it afterwards manual.
# TODO Better way for deletion and keep the desktop in sync without logout/login or desktop dependend cmds?
echo "Deleting HyperHDR desktop icons"
desktop-file-edit --set-key=NoDisplay --set-value=true /usr/share/applications/hyperhdr.desktop 2>/dev/null
rm -v /usr/share/applications/hyperhdr* 2>/dev/null
rm -rv /usr/share/pixmaps/hyperhdr 2>/dev/null

if command -v firewall-cmd &> /dev/null
then
	echo "Firewall: closing port 8090"
	firewall-cmd --remove-port=8090/tcp
fi

exit 0
